import Vue from "vue";
import axios from "axios"
import { Notification } from 'element-ui';

export class Axios {

	constructor () {
		axios.defaults.baseURL = 'http://www.geekhelp.cn/bmy/api';
		axios.defaults.timeout = 30000;
		this.RequestInterceptors();
		this.ResponseInterceptors();
	}

	// 添加请求拦截器
	private RequestInterceptors ():any {

		axios.interceptors.request.use(function (config) {
			// 在发送请求之前做些什么
			return config;
		}, function (error) {
			// 对请求错误做些什么
			return Promise.reject(error);
		});
	}

	// 添加响应拦截器
	private ResponseInterceptors ():any {
		axios.interceptors.response.use(function (response) {
			if(response.data.status == 200) {
				return response;
			} else {
				Notification({
					title: '提示1',
					message: `没有数据 ${response.data.status}`,
				});
				return response;
			}
		}, function (error) {
			Notification({
				title: '提示2',
				message: `请求出错：${JSON.stringify(error.message)}`,
			});
			// 对响应错误做点什么
			return Promise.reject(error);
		});
	}

	/**
	 * get 请求
	 * @param options
	 * {
	 *   url: 请求地址
	 *   params: 请求参数
	 * }
	 */
	public get (options: { url: string, params: object }): Promise<any> {
		return new Promise((resolve, reject) => {
			// @ts-ignore
			axios.get(options.url, {
				// @ts-ignore
				params: options.params

			}).then(function (success) {
				resolve(success);
			}).catch(function (error) {
				console.log(error);
			});
		});
	}

	/**
	 * post 请求
	 * @param options
	 * {
	 *   url: 请求地址
	 *   params: 请求参数
	 * }
	 */
	public post(options: { url: string, params: object, headers?: any }): Promise<any> {
		return new Promise((resolve, reject) => {
			// @ts-ignore
			axios({
				method: 'post',
				url: options.url,
				data: options.params,
				headers: options.hasOwnProperty("headers") ? options.headers : {}
			}).then(function (success) {
				resolve(success.data);
			}).catch(function (error) {
				resolve(error);
			});
		})
	}

}